#include <stdio.h>
#include <sqlite3.h>
#include "./include/sqlite3-wrapper.h"

typedef struct sqlite3_wrapper_object{
	sqlite3 *db;
	int rc;
	char *zErrMsg;
	GSList *list;
} sqlite3_wrapper_object;

static int callback(void *data, int argc, char **argv, char **azColName){
	sqlite3_wrapper_object *obj = (sqlite3_wrapper_object*) data;
	int i;
	obj->list = g_slist_alloc();
	for(i=0; i<argc; i++){
		GString* det = g_string_new(argv[i]);
		obj->list = g_slist_append(obj->list, det);
	}
	return 0;
}

/* object creation */
void* sqlite3_wrapper_create_object(char* database){
	sqlite3_wrapper_object *obj = (sqlite3_wrapper_object*) malloc (sizeof(sqlite3_wrapper_object));

	obj->rc = sqlite3_open(database, &(obj->db));
	if( obj->rc ){
		fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(obj->db));
		sqlite3_close(obj->db);
		return NULL;
	}

	return (void*) obj;
}

/* object removal */
int sqlite3_wrapper_close(void* data){
	sqlite3_wrapper_object *obj = (sqlite3_wrapper_object*) data;
	sqlite3_close(obj->db);
	free(data);
	return 0;
}

/* creation */
/* insert */
/* update */
int sqlite3_wrapper_execute_set(void* data, char* query){
	sqlite3_wrapper_object *obj = (sqlite3_wrapper_object*) data;
	obj->rc = sqlite3_exec(obj->db, query, NULL, 0, &(obj->zErrMsg));
	if( obj->rc!=SQLITE_OK ){
		fprintf(stderr, "SQL error: %s\n", obj->zErrMsg);
		sqlite3_free(obj->zErrMsg);
		return FALSE;
	}
	return TRUE;
}

/* search */
GSList* sqlite3_wrapper_execute_get(void* data, char* query){
	sqlite3_wrapper_object *obj = (sqlite3_wrapper_object*) data;
	obj->rc = sqlite3_exec(obj->db, query, callback, data, &(obj->zErrMsg));
	if( obj->rc!=SQLITE_OK ){
		fprintf(stderr, "SQL error: %s\n", obj->zErrMsg);
		sqlite3_free(obj->zErrMsg);
		return TRUE;
	}
	return obj->list;
}

